class PaymentsController < ApplicationController
  before_action :set_payment, only: [:show, :edit, :update, :destroy]

  # GET /payments
  # GET /payments.json
  def index
    @payments = Payment.all
  end

  # GET /payments/1
  # GET /payments/1.json
  def show
  end

  # GET /payments/new
  def new
    @payment = Payment.new
  end

  # GET /payments/1/edit
  def edit
  end

  # POST /payments
  # POST /payments.json
  def create
    #@payment = Payment.new(payment_params)
    
	@invoice = Invoice.find(params[:invoice_id])
	@payment = @invoice.payments.create(payment_params)

    respond_to do |format|
      if @payment.save
        paymentmethod = PaymentMethod.find(params[:payment][:payment_method_id])
		if paymentmethod.label == "Cash"
			@payment.update(:card_number => 0, :card_provider_id => 1, :card_transaction_ref => "not available" )
		end
      	change = @payment.amount - @invoice.total_fee - @invoice.total_discount
      	@payment.update(:change => change)
        format.html { redirect_to @invoice, notice: 'Payment was successfully created.' }
        format.json { render :show, status: :created, location: @payment }
      else
        format.html { render :new }
        format.json { render json: @payment.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /payments/1
  # PATCH/PUT /payments/1.json
  def update
  	@invoice = Invoice.find(params[:invoice_id])
    respond_to do |format|
      if @payment.update(payment_params)
        format.html { redirect_to @invoice, notice: 'Payment was successfully updated.' }
        format.json { render :show, status: :ok, location: @payment }
      else
        format.html { render :edit }
        format.json { render json: @payment.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /payments/1
  # DELETE /payments/1.json
  def destroy
  	@invoice = Invoice.find(params[:invoice_id])
    @payment.destroy
    respond_to do |format|
      format.html { redirect_to @invoice, notice: 'Payment was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_payment
      @payment = Payment.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def payment_params
      params.require(:payment).permit(:invoice_id, :amount, :change, :payment_method_id, :card_number, :card_provider_id, :card_transaction_ref, :created_at, :updated_at, :created_by, :updated_by)
    end
end
